const express = require('express');
const router = express.Router();
const ApiKey = require('../models/ApiKey');

/**
 * ET客户端专用API密钥接口
 * 为ET移动应用提供安全的API密钥获取服务
 */

// ET客户端认证中间件（简化版，可根据需要增强）
const etClientAuth = (req, res, next) => {
  const clientId = req.headers['x-client-id'];
  const clientSecret = req.headers['x-client-secret'];
  
  // 简单的客户端认证，实际项目中应该使用更安全的方式
  if (clientId === 'ET_CLIENT' && clientSecret === process.env.ET_CLIENT_SECRET || 'et_secret_2024') {
    next();
  } else {
    return res.status(401).json({
      success: false,
      error: '客户端认证失败'
    });
  }
};

/**
 * 获取DeepSeek API密钥
 * GET /api/et/keys/deepseek
 */
router.get('/keys/deepseek', etClientAuth, async (req, res) => {
  try {
    const apiKey = await ApiKey.findOne({
      where: {
        provider: 'deepseek',
        is_active: true
      },
      order: [['usage_count', 'ASC']] // 优先使用使用次数少的密钥
    });
    
    if (!apiKey) {
      return res.status(404).json({
        success: false,
        error: 'DeepSeek API密钥未配置或已禁用'
      });
    }
    
    // 更新使用统计
    await apiKey.updateUsage();
    
    const decryptedKey = apiKey.getDecryptedKey();
    const config = apiKey.api_config || {};
    
    res.json({
      success: true,
      data: {
        api_key: decryptedKey,
        config: {
          baseUrl: config.baseUrl || 'https://api.deepseek.com',
          endpoint: config.endpoint || '/chat/completions',
          models: config.models || ['deepseek-chat', 'deepseek-reasoner'],
          timeout: config.timeout || 60000,
          temperature: config.temperature || 0.7,
          max_tokens: config.max_tokens || 800
        },
        usage_info: {
          usage_count: apiKey.usage_count,
          last_used_at: apiKey.last_used_at,
          daily_limit: apiKey.daily_limit,
          monthly_limit: apiKey.monthly_limit
        }
      }
    });
  } catch (error) {
    console.error('获取DeepSeek API密钥失败:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误'
    });
  }
});

/**
 * 获取火山引擎图片生成API密钥
 * GET /api/et/keys/volcengine
 */
router.get('/keys/volcengine', etClientAuth, async (req, res) => {
  try {
    const apiKey = await ApiKey.findOne({
      where: {
        provider: 'volcengine',
        is_active: true
      },
      order: [['usage_count', 'ASC']]
    });
    
    if (!apiKey) {
      return res.status(404).json({
        success: false,
        error: '火山引擎图片生成API密钥未配置或已禁用'
      });
    }
    
    await apiKey.updateUsage();
    
    const decryptedKey = apiKey.getDecryptedKey();
    const config = apiKey.api_config || {};
    
    res.json({
      success: true,
      data: {
        api_key: decryptedKey,
        config: {
          baseUrl: config.baseUrl || 'https://ark.cn-beijing.volces.com',
          endpoint: config.endpoint || '/api/v3/images/generations',
          model: config.model || 'doubao-seedream-3-0-t2i-250415',
          timeout: config.timeout || 60000
        },
        usage_info: {
          usage_count: apiKey.usage_count,
          last_used_at: apiKey.last_used_at
        }
      }
    });
  } catch (error) {
    console.error('获取火山引擎图片生成API密钥失败:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误'
    });
  }
});

/**
 * 获取火山引擎TTS API配置
 * GET /api/et/keys/volcengine-tts 或 /api/et/keys/volcengine_tts
 */
router.get('/keys/volcengine-tts', etClientAuth, async (req, res) => {
  try {
    const apiKey = await ApiKey.findOne({
      where: {
        provider: 'volcengine_tts',
        is_active: true
      },
      order: [['usage_count', 'ASC']]
    });
    
    if (!apiKey) {
      return res.status(404).json({
        success: false,
        error: '火山引擎TTS API配置未找到或已禁用'
      });
    }
    
    await apiKey.updateUsage();
    
    const config = apiKey.api_config || {};
    
    // ET应用优化的配置格式
    const optimizedConfig = {
      // 核心必需字段（按ET应用期望的顺序）
      appId: String(config.appId || '3581063476'),
      accessToken: String(config.accessToken || apiKey.getDecryptedKey()),
      secretKey: String(config.secretKey || ''),
      cluster: String(config.cluster || 'volcano_tts'),
      resourceId: String(config.resourceId || 'volc.tts.default'),
      
      // 服务端点配置
      baseUrl: String(config.baseUrl || 'https://openspeech.bytedance.com'),
      endpoint: String(config.endpoint || 'https://openspeech.bytedance.com/api/v1/tts'),
      
      // 语音参数
      voice: String(config.voice || 'zh_female_wanqudashu_moon_bigtts'),
      speed: Number(config.speed || 1.0),
      volume: Number(config.volume || 1.0),
      pitch: Number(config.pitch || 1.0),
      
      // 系统配置
      timeout: Number(config.timeout || 30000),
      
      // 服务状态标识
      enabled: true,
      available: true,
      isValid: true,
      serviceReady: true
    };

    res.json({
      success: true,
      data: {
        // ET应用期望的格式
        provider: 'volcengine_tts',
        api_key: String(config.accessToken || apiKey.getDecryptedKey()),
        api_config: optimizedConfig,
        is_active: true,
        usage_count: apiKey.usage_count,
        last_used_at: apiKey.last_used_at,
        // 保持向后兼容
        config: optimizedConfig,
        usage_info: {
          usage_count: apiKey.usage_count,
          last_used_at: apiKey.last_used_at
        },
        validation: {
          hasAllRequiredFields: !!(optimizedConfig.appId && optimizedConfig.accessToken && optimizedConfig.secretKey && optimizedConfig.cluster && optimizedConfig.resourceId),
          configComplete: true,
          serviceEnabled: true
        }
      }
    });
  } catch (error) {
    console.error('获取火山引擎TTS配置失败:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误'
    });
  }
});

// 兼容路由：支持下划线格式
router.get('/keys/volcengine_tts', etClientAuth, async (req, res) => {
  try {
    const apiKey = await ApiKey.findOne({
      where: {
        provider: 'volcengine_tts',
        is_active: true
      },
      order: [['usage_count', 'ASC']]
    });
    
    if (!apiKey) {
      return res.status(404).json({
        success: false,
        error: '火山引擎TTS API配置未找到或已禁用'
      });
    }
    
    await apiKey.updateUsage();
    
    const config = apiKey.api_config || {};
    
    // ET应用优化的配置格式
    const optimizedConfig = {
      // 核心必需字段（按ET应用期望的顺序）
      appId: String(config.appId || '3581063476'),
      accessToken: String(config.accessToken || apiKey.getDecryptedKey()),
      secretKey: String(config.secretKey || ''),
      cluster: String(config.cluster || 'volcano_tts'),
      resourceId: String(config.resourceId || 'volc.tts.default'),
      
      // 服务端点配置
      baseUrl: String(config.baseUrl || 'https://openspeech.bytedance.com'),
      endpoint: String(config.endpoint || 'https://openspeech.bytedance.com/api/v1/tts'),
      
      // 语音参数
      voice: String(config.voice || 'zh_female_wanqudashu_moon_bigtts'),
      speed: Number(config.speed || 1.0),
      volume: Number(config.volume || 1.0),
      pitch: Number(config.pitch || 1.0),
      
      // 系统配置
      timeout: Number(config.timeout || 30000),
      
      // 服务状态标识
      enabled: true,
      available: true,
      isValid: true,
      serviceReady: true
    };

    res.json({
      success: true,
      data: {
        // ET应用期望的格式
        provider: 'volcengine_tts',
        api_key: String(config.accessToken || apiKey.getDecryptedKey()),
        api_config: optimizedConfig,
        is_active: true,
        usage_count: apiKey.usage_count,
        last_used_at: apiKey.last_used_at,
        // 保持向后兼容
        config: optimizedConfig,
        usage_info: {
          usage_count: apiKey.usage_count,
          last_used_at: apiKey.last_used_at
        },
        validation: {
          hasAllRequiredFields: !!(optimizedConfig.appId && optimizedConfig.accessToken && optimizedConfig.secretKey && optimizedConfig.cluster && optimizedConfig.resourceId),
          configComplete: true,
          serviceEnabled: true
        }
      }
    });
  } catch (error) {
    console.error('获取火山引擎TTS配置失败:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误'
    });
  }
});

/**
 * 获取所有可用的API密钥配置
 * GET /api/et/keys/all
 */
router.get('/keys/all', etClientAuth, async (req, res) => {
  try {
    const apiKeys = await ApiKey.findAll({
      where: {
        is_active: true
      },
      attributes: ['id', 'name', 'provider', 'usage_count', 'last_used_at', 'api_config'],
      order: [['provider', 'ASC'], ['usage_count', 'ASC']]
    });
    
    const result = {};
    
    for (const key of apiKeys) {
      const decryptedKey = key.getDecryptedKey();
      const config = key.api_config || {};
      
      result[key.provider] = {
        name: key.name,
        api_key: decryptedKey,
        config: config,
        usage_info: {
          usage_count: key.usage_count,
          last_used_at: key.last_used_at
        }
      };
      
      // 更新使用统计
      await key.updateUsage();
    }
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('获取所有API密钥失败:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误'
    });
  }
});

/**
 * 调试接口：获取volcengine_tts的详细配置信息
 * GET /api/et/keys/volcengine_tts/debug
 */
router.get('/keys/volcengine_tts/debug', etClientAuth, async (req, res) => {
  try {
    const apiKey = await ApiKey.findOne({
      where: {
        provider: 'volcengine_tts',
        is_active: true
      },
      order: [['usage_count', 'ASC']]
    });
    
    if (!apiKey) {
      return res.status(404).json({
        success: false,
        error: '火山引擎TTS API配置未找到或已禁用'
      });
    }
    
    const config = apiKey.api_config || {};
    const decryptedKey = apiKey.getDecryptedKey();
    
    // 详细的调试信息
    res.json({
      success: true,
      debug_info: {
        raw_config: config,
        decrypted_key_available: !!decryptedKey,
        decrypted_key_length: decryptedKey ? decryptedKey.length : 0,
        processed_config: {
          appId: String(config.appId || '3581063476'),
          accessToken: String(config.accessToken || decryptedKey),
          secretKey: String(config.secretKey || ''),
          cluster: String(config.cluster || 'volcano_tts'),
          resourceId: String(config.resourceId || 'volc.tts.default'),
          baseUrl: String(config.baseUrl || 'https://openspeech.bytedance.com'),
          endpoint: String(config.endpoint || 'https://openspeech.bytedance.com/api/v1/tts'),
          voice: String(config.voice || 'zh_female_wanqudashu_moon_bigtts'),
          speed: Number(config.speed || 1.0),
          volume: Number(config.volume || 1.0),
          pitch: Number(config.pitch || 1.0),
          timeout: Number(config.timeout || 30000),
          enabled: true,
          available: true
        },
        field_types: {
          appId: typeof String(config.appId || '3581063476'),
          accessToken: typeof String(config.accessToken || decryptedKey),
          secretKey: typeof String(config.secretKey || ''),
          cluster: typeof String(config.cluster || 'volcano_tts'),
          resourceId: typeof String(config.resourceId || 'volc.tts.default')
        }
      }
    });
  } catch (error) {
    console.error('调试volcengine_tts配置失败:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误',
      debug_error: error.message
    });
  }
});

/**
 * 检查API密钥状态
 * GET /api/et/keys/status
 */
router.get('/keys/status', etClientAuth, async (req, res) => {
  try {
    const providers = ['deepseek', 'volcengine', 'volcengine_tts'];
    const status = {};
    
    for (const provider of providers) {
      const apiKey = await ApiKey.findOne({
        where: {
          provider: provider,
          is_active: true
        }
      });
      
      status[provider] = {
        available: !!apiKey,
        usage_count: apiKey ? apiKey.usage_count : 0,
        last_used_at: apiKey ? apiKey.last_used_at : null
      };
    }
    
    res.json({
      success: true,
      data: status
    });
  } catch (error) {
    console.error('检查API密钥状态失败:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误'
    });
  }
});

/**
 * 报告API密钥使用情况（可选）
 * POST /api/et/keys/usage-report
 */
router.post('/usage-report', etClientAuth, async (req, res) => {
  try {
    const { provider, success, error_message } = req.body;
    
    if (!provider) {
      return res.status(400).json({
        success: false,
        error: '缺少provider参数'
      });
    }
    
    const apiKey = await ApiKey.findOne({
      where: {
        provider: provider,
        is_active: true
      }
    });
    
    if (apiKey) {
      // 可以在这里记录使用情况，添加错误日志等
      console.log(`API密钥使用报告 - Provider: ${provider}, Success: ${success}, Error: ${error_message || 'None'}`);
    }
    
    res.json({
      success: true,
      message: '使用报告已记录'
    });
  } catch (error) {
    console.error('记录API密钥使用报告失败:', error);
    res.status(500).json({
      success: false,
      error: '服务器内部错误'
    });
  }
});

module.exports = router;